package ipad.asia.controller;

import ipad.asia.dao.AdminDao;
import ipad.asia.entity.Admin;
import ipad.asia.service.AdminService;
import ipad.asia.utils.MyTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminDao adminDao;
    MyTime mytime=new MyTime();

    /**
     * 管理员登录
     */
    @RequestMapping("/admin/login")
    public boolean login(@RequestParam(value = "user",required = false) String user,
                         @RequestParam(value = "password", required = false) String password)  {
        if(adminDao.findByUserAndPassword(user, password)==null){
            return false;
        }else {return true;}
    }
    /**
     * 注册
     * @param user
     * @param password
     * @param email
     * @param phone
     * @return
     */
    @PostMapping("/admin/register")
    public boolean register(@RequestParam(value = "user") String user,
                            @RequestParam(value = "password") String password,
                            @RequestParam(value = "email",required = false) String email,
                            @RequestParam(value = "phone",required = false) Integer phone) {
        if(user==null){return false;}else{
            if (adminService.findByUser(user).isEmpty()) {
                Admin admin=new Admin();
                admin.setUser(user).setPassword(password)
                        .setEmail(email).setPhone(phone).setDate(mytime.LocalDateTime());
                adminService.save(admin);
                return true; } else { return false;
            }}
    }
    /**
     * 查找id，用作session
     * @param id
     * @return
     */
    @RequestMapping("/admin/get")
    public Admin get(@RequestParam("id") int id) throws Exception {
        if(adminService.findById(id)!=null){
            return adminService.findById(id);}else {throw new Exception();}
    }
}
